package com.example.demotest.controller;

import com.example.demotest.pojo.*;
import com.example.demotest.pojo.dto.AdminDto;
import com.example.demotest.pojo.dto.UserDto;
import com.example.demotest.repository.ProductCategoryRepository;
import com.example.demotest.repository.ProductRepository;
import com.example.demotest.repository.UserRepository;
import com.example.demotest.service.AdminService;
import com.example.demotest.service.IAdminService;
import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.*;
import jakarta.persistence.criteria.Predicate; // ✅ 正确的
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    IAdminService adminService; // 注入 service

    @Autowired
    private JWT jwt;//于登录验证和提取用户信息

    @Autowired
    private ProductCategoryRepository categoryRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //管理员注册
    // 注册接口（安全版）
    @PostMapping("/register")
    public ResponseMessage<Admin> register(@Validated @RequestBody AdminDto adminDto) {
        System.out.println("管理员注册的接受成功");
        Admin newAdmin = adminService.register(adminDto);
        return ResponseMessage.success(newAdmin);
    }

    // 管理员登录接口
    @PostMapping("/login")
    public ResponseMessage<Admin> login(@RequestBody AdminDto adminDto) {
        return adminService.login(adminDto);
    }

    @Transactional
    @PostMapping("/category/add")
    public ResponseMessage<String> addCategory(@RequestBody String categoryName, HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.isAdmin(token)) {
            return ResponseMessage.error(403, "权限不足：仅管理员可添加分类");
        }

        if (categoryName == null || categoryName.trim().isEmpty()) {
            return ResponseMessage.error(400, "分类名称不能为空");
        }

        // 检查是否已存在
        if (categoryRepository.findByName(categoryName.trim()).isPresent()) {
            return ResponseMessage.error(409, "分类已存在：" + categoryName.trim());
        }

        // 保存新分类
        ProductCategory category = new ProductCategory();
        category.setName(categoryName.trim());
        categoryRepository.save(category);

        return ResponseMessage.success("添加成功：" + categoryName.trim());
    }

    @Value("${spring.data.web.pageable.default-page-size:8}")
    private int defaultPageSize;

    @GetMapping("/idleList")
    public ResponseEntity<?> getIdleList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "8") int nums,
            @RequestParam(required = false) String statusCheck,
            @RequestParam(required = false) String statusSold
    ) {
        Pageable pageable = PageRequest.of(page - 1, nums, Sort.by(Sort.Direction.DESC, "createdAt"));

        Specification<Product> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (statusCheck != null) {
                predicates.add(cb.equal(root.get("statusCheck"), ProductCheckStatus.valueOf(statusCheck.toUpperCase())));
            }
            if (statusSold != null) {
                predicates.add(cb.equal(root.get("statusSold"), ProductSoldStatus.valueOf(statusSold.toUpperCase())));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };

        Page<Product> result = productRepository.findAll(spec, pageable);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.getContent());
        data.put("count", result.getTotalElements());

        return ResponseEntity.ok(Map.of(
                "status_code", 1,
                "data", data
        ));
    }



    @PutMapping("/updateIdleStatus")
    public ResponseEntity<?> updateIdleStatus(@RequestBody Map<String, Object> payload) {
        Integer id = ((Number) payload.get("id")).intValue();
        String statusCheck = (String) payload.get("statusCheck");
        String statusSold = (String) payload.get("statusSold");

        Optional<Product> optionalProduct = productRepository.findById(id);
        if (optionalProduct.isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "status_code", 0,
                    "msg", "商品不存在"
            ));
        }

        Product product = optionalProduct.get();

        if (statusCheck != null) {
            product.setStatusCheck(ProductCheckStatus.valueOf(statusCheck));
        }

        if (statusSold != null) {
            product.setStatusSold(ProductSoldStatus.valueOf(statusSold));
        }

        productRepository.save(product);

        return ResponseEntity.ok(Map.of(
                "status_code", 1,
                "msg", "商品状态更新成功"
        ));
    }

    @PostMapping("/deleteGoods")
    public ResponseEntity<?> deleteGoods(@RequestBody Map<String, Integer> body) {
        Integer id = body.get("id");

        if (id == null) {
            return ResponseEntity.badRequest().body(Map.of(
                    "status_code", 0,
                    "msg", "商品ID不能为空"
            ));
        }

        Optional<Product> optionalProduct = productRepository.findById(id);
        if (optionalProduct.isEmpty()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of(
                    "status_code", 0,
                    "msg", "未找到对应商品"
            ));
        }

        productRepository.deleteById(id);

        return ResponseEntity.ok(Map.of(
                "status_code", 1,
                "msg", "删除成功"
        ));
    }

    @GetMapping("/userList")
    public ResponseEntity<?> getUserList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "8") int nums,
            @RequestParam(required = false) Integer status
    ) {
        try {
            System.out.println("Received request - page: " + page + ", nums: " + nums + ", status: " + status);
            
            Pageable pageable = PageRequest.of(page - 1, nums, Sort.by(Sort.Direction.DESC, "userId"));

            Page<User> result = userRepository.findAll(pageable);
            System.out.println("Found " + result.getTotalElements() + " users");

            List<UserDto> userDtos = result.getContent().stream().map(user -> {
                UserDto dto = new UserDto();
                dto.setUserID(user.getUserId());
                dto.setUserName(user.getUserName());
                dto.setNickname(user.getNickname());
                dto.setAvatarUrl(user.getAvatarUrl());
                return dto;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("list", userDtos);
            data.put("count", result.getTotalElements());

            return ResponseEntity.ok(Map.of(
                    "status_code", 1,
                    "data", data
            ));
        } catch (Exception e) {
            System.err.println("Error in getUserList: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status_code", 0,
                            "msg", "获取用户列表失败: " + e.getMessage()
                    ));
        }
    }

    @GetMapping("/updateUserStatus")
    public ResponseEntity<?> updateUserStatus(
            @RequestParam Integer id,
            @RequestParam Integer status
    ) {
        try {
            System.out.println("Updating user status - id: " + id + ", status: " + status);
            
            Optional<User> optionalUser = userRepository.findById(id);
            if (optionalUser.isEmpty()) {
                return ResponseEntity.ok(Map.of(
                        "status_code", 0,
                        "msg", "用户不存在"
                ));
            }

            User user = optionalUser.get();
            User.UserStatus userStatus = status == 0 ? User.UserStatus.IN : User.UserStatus.FROZEN;
            user.setStatus(userStatus);
            userRepository.save(user);

            System.out.println("Successfully updated user status for user: " + id);
            
            return ResponseEntity.ok(Map.of(
                    "status_code", 1,
                    "msg", "用户状态更新成功"
            ));
        } catch (Exception e) {
            System.err.println("Error in updateUserStatus: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status_code", 0,
                            "msg", "更新用户状态失败: " + e.getMessage()
                    ));
        }
    }

    @PostMapping("/resetUserPassword")
    public ResponseEntity<?> resetUserPassword(@RequestBody Map<String, Integer> body, HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.isAdmin(token)) {
            return ResponseEntity.ok(Map.of(
                    "status_code", 0,
                    "msg", "权限不足：仅管理员可重置密码"
            ));
        }

        Integer userId = body.get("id");
        if (userId == null) {
            return ResponseEntity.ok(Map.of(
                    "status_code", 0,
                    "msg", "用户ID不能为空"
            ));
        }

        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "status_code", 0,
                    "msg", "用户不存在"
            ));
        }

        User user = optionalUser.get();
        user.setPassword(passwordEncoder.encode("123456"));
        userRepository.save(user);

        return ResponseEntity.ok(Map.of(
                "status_code", 1,
                "msg", "密码重置成功"
        ));
    }
}
